package com.cyk.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/download")
public class DownLoad extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得要下载的文件的名称
		String filename = request.getParameter("filename"); // 美女.jpg
		// 解决获得中文参数的乱码
//        filename = new String(filename.getBytes("GBK"),"UTF-8");

		// 根据获取的文件名设置要下载的文件类型
		response.setContentType(this.getServletContext().getMimeType(filename));
		// 告诉浏览器不要解析次文件直接下载 ，没有这一行的话 浏览器会默认打开.
		//后面的 java.net.URLEncoder.encode(filename,"UTF-8")是把文件名子编码，让浏览器下载的时候文件名不会乱码
		response.setHeader("content-disposition",
				"attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
		// 获取文件的绝对路径
		String path = this.getServletContext().getRealPath("image/" + filename);
		System.out.println("path:"+path);
		// 获得该文件的输入流
		InputStream in = new FileInputStream(path);
		// 获得输出流 通过response获得输出流，用于向客户端输出内容
		ServletOutputStream out = response.getOutputStream();
		// 文件拷贝的模板代码
		int len = 0;
		//设定1k的字节数组
		byte[] buffer = new byte[1024];
		//从输入流中读出数据（每次1024字节）并根据返回值判断是否读取完毕，读取完毕会返回0
		while ((len = in.read(buffer)) > 0) {
			//System.out.println(len);
			//从0字节开始写入到客户端，每次写入指定大小的字节，直到写入结束
			out.write(buffer, 0, len);
		}
		in.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}
